﻿#include "SerialCom.h"
#include <QUrl>
#include <QDebug>
#include <QTimer>
#include <QRegularExpression>

#pragma execution_character_set("utf-8")

SerialCom::SerialCom(QObject *parent)
    : ComBase(parent),
      mSerial(new QSerialPort(this))
{
    connect(mSerial, &QSerialPort::errorOccurred, this, &SerialCom::onErrorOccured);
    connect(mSerial, &QSerialPort::readyRead, this, &SerialCom::onReadyRead);
}

void SerialCom::onInit()
{
    if (!mSerial) {
         qDebug() << "serial not init!";
    }
    if(mSerial->isOpen()){
        mSerial->close();
    }
    mSerial->setPortName(mConfig.serial.comId);
    mSerial->setBaudRate(mConfig.serial.baudRate);
    mSerial->setDataBits(mConfig.serial.dataBits);
    mSerial->setParity(mConfig.serial.parity);
    mSerial->setStopBits(mConfig.serial.stopBits);
    mSerial->setFlowControl(mConfig.serial.flowControl);
    if (mSerial->open(QIODevice::ReadWrite)) {
        setState(CS_Connected);
    } else {
        setState(CS_UnConnected);
    }
}

void SerialCom::onQuit()
{
    if(mSerial != nullptr){
        if(mSerial->isOpen())
            mSerial->close();
        mSerial->deleteLater();
        mSerial = nullptr;
    }
    deleteLater();
}

void SerialCom::writeData(const QByteArray& data)
{
    if(mSerial == nullptr)
        return;
    qint64 reply = mSerial->write(data);
    if(reply == -1){
        emit sigMsg(tr("<font color=\'red\'>发送失败:%1</font>") + mSerial->errorString());
    }
}

void SerialCom::onReadyRead()
{
    auto data = mSerial->readAll();
    if(data.length() < 1){
        return;
    }
    emit sigReceiveData(data);
    processData(data);
}

void SerialCom::processData(const QByteArray &data)
{

}

void SerialCom::onErrorOccured(QSerialPort::SerialPortError newError)
{
    if (newError == QSerialPort::SerialPortError::NoError || !mSerial)
        return;
    setState(CS_UnConnected);
    emit sigMsg(QString(tr("<font color=\'red\'>%1</font>")).arg(mSerial->errorString()));
}

void SerialCom::disconnect()
{
    if(mSerial != nullptr){
        if(mSerial->isOpen())
            mSerial->close();
    }
}
